// 行情中心首页 > A股 > 排行 > A股涨幅
// https://vip.stock.finance.sina.com.cn/mkt/#stock_hs_up
use crate::REQWEST_CLIENT;
use anyhow::Result;
use serde::{ Deserialize, Serialize };
/// Mapping to [stock_hs_up.json](file:///Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/sina/src/stock_hs_up.json)
#[derive(Debug, Serialize, Deserialize)]
pub struct StockA {
    symbol: String,
    code: String,
    name: String,
    trade: String,
    pricechange: f64,
    changepercent: f64,
    buy: String,
    sell: String,
    settlement: String,
    open: String,
    high: String,
    low: String,
    volume: u64,
    amount: u64,
    ticktime: String,
    per: f64,
    pb: f64,
    mktcap: f64,
    nmc: f64,
    turnoverratio: f64,
}

impl StockA {
    /// ## [行情中心首页 > A 股 > 排行 > A 股跌幅](https://vip.stock.finance.sina.com.cn/mkt/#stock_hs_up)
    /// - [通过Chrome-Dev-Tool找 quotes_service 分页](https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=80&sort=changepercent&asc=0&node=hs_a&symbol=&_s_r_a=setlen)
    ///
    pub async fn hang_qing(page: u32) -> Result<Vec<StockA>> {
        // GET /api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1815_stock_snapshot&TABKEY=tab1&PAGENO=2&tab1PAGESIZE=10&txtBeginDate=2024-02-08&txtEndDate=2024-02-08&archiveDate=2022-02-07&random=0.8786228249620156 HTTP/1.1
        // Accept: application/json, text/javascript, */*; q=0.01
        // Accept-Encoding: gzip, deflate, br
        // Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
        // Connection: keep-alive
        // Content-Type: application/json
        // Host: www.szse.cn
        // Referer: https://www.szse.cn/market/trend/index.html
        // Sec-Fetch-Dest: empty
        // Sec-Fetch-Mode: cors
        // Sec-Fetch-Site: same-origin
        // User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
        // X-Request-Type: ajax
        // X-Requested-With: XMLHttpRequest
        // sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"
        // sec-ch-ua-mobile: ?0
        // sec-ch-ua-platform: "macOS"

        let request_url = format!(
            "https://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page={page}&num=80&sort=symbol&asc=0&node=hs_a&symbol=&_s_r_a=sort"
        );
        let mut response = REQWEST_CLIENT.get(request_url)
            .header(reqwest::header::ACCEPT, "*/*")
            .header("Accept-Encoding", "gzip, deflate, br")
            .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
            .header("Cache-Control", "no-cache")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .header(
                "Cookie",
                "SUB=_2AkMSyzIYf8NxqwFRmfoRzWjgb451yQ_EieKkl8PDJRMyHRl-yD8XqlMltRB6OUsc97NmXds_hQWHHftnIsJVziKqMZ3l; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9W5lbX4MXHwgd1fVObfy7fre; UOR=,finance.sina.com.cn,; SR_SEL=1_511; SINAGLOBAL=43.242.142.226_1705047833.427480; Apache=43.242.142.226_1705047833.427482; ULV=1705048712538:2:2:2:43.242.142.226_1705047833.427482:1705047824795; SFA_version7.11.0_click=1; U_TRS1=000000e2.bdaba816d.65c1f03e.c76804ef; U_TRS2=000000e2.bdb4a816d.65c1f03e.108f1f60; visited_funds=513130; FIN_ALL_VISITED=sz399552%2Cbj833575%2Csh513130; FINA_V_S_2=sz399552; FINA_V5_HQ=0; FINA_DMHQ=1; SFA_version7.11.0=2024-02-18%2015%3A12; rotatecount=3; FSINAGLOBAL=43.242.142.226_1705047833.427480"
            )
            .header("Pragma", "no-cache")
            .header("Referer", "https://vip.stock.finance.sina.com.cn/mkt/")
            .header(
                "Sec-Ch-Ua",
                "\"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\", \"Chromium\";v=\"121\""
            )
            .header("Sec-Ch-Ua-Mobile", "?0")
            .header("Sec-Ch-Ua-Platform", "\"macOS\"")
            .header("Sec-Fetch-Dest", "empty")
            .header("Sec-Fetch-Mode", "cors")
            .header("Sec-Fetch-Site", "same-origin")
            .header(
                "User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
            )
            .send().await?;

        let mut body = Vec::new();

        // handling Transfer-Encoding: chunked
        while let Some(chunk) = response.chunk().await.unwrap() {
            body.extend_from_slice(&chunk);
        }

        let body_str = String::from_utf8(body)?;

        // println!("*** body={}\n\nhangqin\n\n", body_str);

        let hangqin_vec: Vec<StockA> = serde_json::from_str(&body_str)?;

        // println!("{:?}", hangqin_vec);

        Ok(hangqin_vec)
    }
}

pub fn add_two_numbers(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod test {
    use std::{ fs::File, io::BufReader };

    use super::*;

    #[test]
    fn test_stock_hs_up_json_file() {
        let path =
            "/Users/CC/gitee/conanchen/fuquants-workspace/crates/fudacli/sina/src/stock_hs_up.json";

        // Open the JSON path and read its contents
        let path = File::open(path).expect(&format!("Failed to open path={}", path));
        let reader = BufReader::new(path);

        // Parse the JSON data into the Data struct
        let hangqin_vec: Vec<StockA> = serde_json
            ::from_reader(reader)
            .expect("Failed to parse JSON");

        assert_eq!(hangqin_vec.len(), 3);
    }

    #[tokio::test]
    async fn test_stock_a_hang_qing() {
        let result = StockA::hang_qing(2).await;

        assert_eq!(result.is_ok(), true);
        if let Ok(data) = result {
            println!("data[0]={:?}", data.first());
            assert_eq!(data.len() > 1, true);
        }
    }

    #[test]
    fn adds_two_positive_numbers() {
        let result = add_two_numbers(2, 3);
        assert_eq!(result, 5);
    }

    #[test]
    fn adds_two_negative_numbers() {
        let result = add_two_numbers(-2, -3);
        assert_eq!(result, -5);
    }

    #[test]
    fn adds_positive_and_negative_number() {
        let result = add_two_numbers(2, -3);
        assert_eq!(result, -1);
    }
}
